﻿Imports System.Data
Imports System.IO
Imports amod2
Imports formulare

Public Class Main


#Region "private attributes"


    Private aSettingsPathForDBGen As String     ' cesta kde sa ulozi fyzicka databaza /dano
    Dim aPathKroslibProject As String       ' cesta k vbproj suboru kroslibu    
    Dim aPathKroslibProjectFile As String
    Dim aSolutionWorker As SourceCode_worker         'ostane objekt na vytvaranie solution
    Dim aDbGen As New DBGen()                        'ostane objekt na vytvaranie databazy
    Dim aFrmGen As GeneratorFormularov               'ostane objekt na vytvaranie formularom
    Dim aModulesDict As New List(Of ModulAtributes)   'meno modulu + cesta k prislusnemu amodu
    Dim aPathRootTemplate As String                     ' cesta ku root adresaru s templatmi
    Dim aDbGenSettings As DBGenSettings              ' objekt nastaveni generatora databazi
    Dim aPathDestination As String                      ' cielovy adresar kam sa vygeneruje projekt
    Dim aProjectName As String                         ' nazov solution
    Dim aSolutionName As String
    Dim aFileNames As New Files()                             ' nazvi suborov a templatov
    Dim aExportSettings As ExportSettings               ' setting na generovanie formularov


#End Region


    ''' <summary>
    ''' konstruktor
    ''' </summary>
    ''' <param name="pPathRootTemplate">Root adresar k templatom</param>
    ''' <param name="pDbGenSettings">Nastavenie DB Generatora</param>
    ''' <param name="pPathDestination">Root adresar kde sa vytvorit Novy Solution(v tomto Root adresary sa nachadza aj Amod Solution subor)</param>
    ''' <param name="pProjectName">Nazov vysledneho Solution(takto sa bude volat subor SLN) a takto by sa mal volat adresar v ktorom su podadresare s modulmi</param>
    ''' <remarks></remarks>
    Public Sub New(ByVal pPathRootTemplate As String, ByVal pDbGenSettings As DBGenSettings, ByVal pPathDestination As String, ByVal pProjectName As String, ByVal pExportSettings As ExportSettings)
        If (pPathRootTemplate.Length = 0) Then
            Throw New Exception("Takato cesta k root adresaru k templatmi neexistuje")
        End If
        If (pPathDestination.Length = 0) Then
            Throw New Exception("Takato cielova cesta neexistuje")
        End If
        If (pProjectName.Length = 0) Then
            Throw New Exception("Nazov projektu musi byt zadany")
        End If

        Me.aPathDestination = pPathDestination
        Me.aDbGenSettings = pDbGenSettings
        Me.aPathRootTemplate = pPathRootTemplate
        Me.aProjectName = pProjectName
        Me.aSolutionName = pProjectName
        Me.aSolutionWorker = New SourceCode_worker(Me.aFileNames, pPathRootTemplate, pPathDestination, pProjectName)
        Me.aExportSettings = pExportSettings
    End Sub
    ''' <summary>
    ''' pre generovanie databazy
    ''' </summary>
    ''' <param name="pDbGenSettings">nastavenie DB generatora</param>
    ''' <remarks></remarks>
    Public Sub New(ByVal pDbGenSettings As DBGenSettings, ByVal pPathDestination As String, ByVal pExportSettings As ExportSettings)
        Me.aDbGenSettings = pDbGenSettings
        Me.aPathDestination = pPathDestination
        aExportSettings = pExportSettings
    End Sub


#Region "Private methods"
    ''' <summary>
    ''' vtati kod pre init component cast
    ''' </summary>
    ''' <param name="pName"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function GetComponentInitsCode(ByVal pName As String) As String
        Return "Me." & pName & " = New System.Windows.Forms.Button" & vbCrLf
    End Function
    ''' <summary>
    ''' vtati kod pre setting component cast
    ''' </summary>
    ''' <param name="pName"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function GetComponenttSettingsCode(ByVal pName As String, ByVal x As Integer, ByVal y As Integer) As String
        Return "'" & pName & "'" & vbCrLf & _
                      "Me." & pName & ".Location = New System.Drawing.Point(" & x & ", " & y & ")" & vbCrLf & _
                      "Me." & pName & ".Name = """ & pName & """" & vbCrLf & _
                      "Me." & pName & ".Size = New System.Drawing.Size(220, 23)" & vbCrLf & _
                      "Me." & pName & ".TabIndex = 0" & vbCrLf & _
                      "Me." & pName & ".Text = """ & pName & """" & vbCrLf & _
                      "Me." & pName & ".UseVisualStyleBackColor = True" & vbCrLf
    End Function
    ''' <summary>
    ''' vrati kod pre unit registraciu pohladoveho formularu
    ''' </summary>
    ''' <param name="pModul"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function getUnitRegVw(ByVal pModul As String)
        Dim lUnitsPart As String
        lUnitsPart = vbCrLf & vbCrLf & "' List_View_" & pModul
        lUnitsPart = lUnitsPart & vbCrLf & "u = New Unit(""List_" & pModul & """)"
        lUnitsPart = lUnitsPart & vbCrLf & "u.AddFrm(GetType(" & Me.aFileNames.mPrefixFrm & pModul & "), ""VIEW_" & pModul & """)"
        lUnitsPart = lUnitsPart & vbCrLf & "u.AddTables(""VIEW_" & pModul & """)"
        lUnitsPart = lUnitsPart & vbCrLf & "Me.AddListUnit(u)"
        Return lUnitsPart
    End Function
    ''' <summary>
    ''' vrati kod pre unit registraciu formularov
    ''' </summary>
    ''' <param name="pUnits"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function getUnitReg(ByVal pUnits As List(Of String))
        Dim lUnitsPart As String = ""
        For Each lUnitName As String In pUnits
            lUnitsPart = lUnitsPart & vbCrLf & vbCrLf & "'" & lUnitName
            lUnitsPart = lUnitsPart & vbCrLf & "u = New Unit(""" & lUnitName & """)"
            lUnitsPart = lUnitsPart & vbCrLf & "u.AddFrm(GetType(" & Me.aFileNames.mPrefixFrm & lUnitName & "), """ & Me.aFileNames.mPrefixFrm & lUnitName & """)"
            lUnitsPart = lUnitsPart & vbCrLf & "u.AddLog(GetType(" & Me.aFileNames.mPrefixLog & lUnitName & "), """ & Me.aFileNames.mPrefixLog & lUnitName & """)"
            lUnitsPart = lUnitsPart & vbCrLf & "u.AddTables(""" & lUnitName & """)"
            lUnitsPart = lUnitsPart & vbCrLf & "Me.AddUnit(u)"
        Next
        Return lUnitsPart
    End Function


    ''' <summary>
    ''' vtati kod pre add component cast
    ''' </summary>
    ''' <param name="pName"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function GetComponentAddsCode(ByVal pName As String) As String
        Return "Me.Controls.Add(Me." & pName & ")" & vbCrLf
    End Function
    ''' <summary>
    ''' vtati kod pre friend component cast
    ''' </summary>
    ''' <param name="pName"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function GetComponentFriendsCode(ByVal pName As String) As String
        Return "Friend WithEvents " & pName & " As System.Windows.Forms.Button" & vbCrLf
    End Function
    ''' <summary>
    ''' vtati kod pre click component cast
    ''' </summary>
    ''' <param name="pName"></param>
    ''' <param name="pUnitName"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function GetComponentClicksCode(ByVal pName As String, ByVal pUnitName As String) As String
        Return "Private Sub " & pName & "_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles " & pName & ".Click" & vbCrLf & _
                    "Dim frm As New frm_" & pUnitName & "()" & vbCrLf & _
                    "frm.ShowDialog()" & vbCrLf & _
                    "End Sub" & vbCrLf
    End Function

    Private Sub GenerateOneFormular(ByVal pMOdules As List(Of ModulAtributes), ByVal pModul As String, ByVal pHumanModul As String, ByVal pVersionName As String, ByVal pModulPath As String, ByVal pUnit As String, ByVal overwrite As Boolean)

        Dim aDat As Dat
        Dim aOneDataset As DsAModOneVersion ' dataset jednej verzie z ktoreho sa bude generovat databaza
        Dim aVersion As String

        ' nacitat settings pre DB Generator
        Dim aDlgDBGen As New DlgDBGenerator()
        If (Me.DBGeneratorSettings IsNot Nothing) Then    ' ak eksistuje uz nastavenie
            aDlgDBGen.SetComponents(Me.DBGeneratorSettings)
        End If
        aDlgDBGen.giveData(Me) ' prerobit na konstruktor a aby vracal denSettings ako navrat hodnotu
        aDlgDBGen.ShowDialog()

        ' 2 krok - vygenerovanie databazy na disk na urcene miesto
        Dim wantGenerate As Boolean = True

        If (Me.aDbGenSettings Is Nothing) Then
            MessageBox.Show("Nenastavili Ste generator - nebude vytvorena DB")
            wantGenerate = False
        End If
        If (wantGenerate = True) Then
            If (Me.DBGeneratorSettings.areSettingsCorrect() = False) Then

                MessageBox.Show("Nenastavili ste nastavenia pre Databázový generátor. Z tohto dôvodu nebude vygenerovana Databáza.")
            Else
                'Dim modulAtr As New ModulAtributes(pModul, pHumanModul, pVersionName, pModulPath)
                'Me.aModulesDict.Add(modulAtr)
                Me.DBGenerator.generateWholeDatabaseScript(Me.aDbGenSettings, pMOdules)

                Try
                    SQL_worker.createDB(Me.aDbGenSettings.DbName, Me.DBGenerator.ScriptDatabaseCreate, Me.DBGenerator.ScriptTablesCreate, Me.DBGenerator.ScriptSystem, Me.DBGeneratorSettings.ServerName)
                Catch e As Exception
                    MessageBox.Show("Chyba - Nepodarilo sa vytvorit Databazu " + e.Message)
                End Try
            End If
        End If
        aDat = New Dat(pModul, pHumanModul, pVersionName)
        ' 3 krok - pridanie formularov do adresarov modulov v novom projekte
        Dim aPathTemplateComponents As String = Me.aPathRootTemplate & "\" & Me.aFileNames.mFolderFormTemplates & "\" & Me.aFileNames.mFileFormComponents
        aDat.LoadDsComponents(aPathTemplateComponents)

        Me.aFrmGen = New GeneratorFormularov(Path.Combine(Me.aPathRootTemplate, Me.aFileNames.mFolderFormTemplates), aDat)

        aDat.LoadAMod(pModulPath, "CHYBA - Nepodarilo sa otvoriť Amod súbor pri generovaní databázy.")
        ' nastavi sa verzia a nacita konkretny dataset podla verzie






        If (wantGenerate = True) Then

            If (Me.aDbGenSettings.Ver = -1) Then
                aVersion = aDat.GetLastVersion.ToString()
                aOneDataset = aDat.GetVersionDataset(aVersion) 'ak ide o poslednu verziu
            Else
                If (wantGenerate = False) Then
                    aVersion = -1
                Else
                    aVersion = Me.aDbGenSettings.Ver
                End If
                aOneDataset = aDat.GetVersionDataset(aVersion)
            End If

        Else
            aVersion = aDat.GetLastVersion.ToString()
            aOneDataset = aDat.GetVersionDataset(aVersion)
        End If


        For Each aDataRow As DataRow In aOneDataset.Tables(aOneDataset.UnitsTable.TableName).Rows
            Dim aUnitName As String = (aDataRow("UnitName"))
            'aUnits.Add(aUnitName)

            If (aUnitName = pUnit) Then


                'aFrmGen.Exportuj(Me.aPathDestination & "\" & Me.aProjectName & "\" & Me.aFileNames.mFolderModules & "\" & pModul, kkVariant.Detaily_a_prvy_grid_v_prvom_tabe, aUnitName, Me.aPathDestination & "\" & Me.aProjectName & "\" & Me.aFileNames.mFolderModules & "\" & pModul, aExportSettings)


                'Dim aFrmFormulareExport As FrmFormulareExport = New FrmFormulareExport(Me.aPathDestination & "\" & Me.aProjectName & "\" & Me.aFileNames.mFolderModules & "\" & pModul, aUnitName, aFrmGen, aExportSettings, aDat.GetLastVersion, "Zoznamovy Form")
                'aFrmFormulareExport.ShowDialog()

                Dim lMyPath As String = Me.aPathDestination & "\" & Me.aProjectName & "\" & Me.aFileNames.mFolderModules & "\" & pModul
                aFrmGen.Exportuj(aUnitName, lMyPath, aExportSettings, aDat.GetLastVersion)

                ' zmenim referencie na
                If (overwrite = False) Then

                    Dim lComponentsInit As String = ""
                    Dim lComponentsSetting As String = ""
                    Dim lComponentsAdd As String = ""
                    Dim lComponentsFriend As String = ""
                    Dim lComponentClickCode As String = ""

                    Dim aOtherFiles As New List(Of String)()
                    Dim aResxFiles As New Dictionary(Of String, String)
                    Dim aVBFiles As New List(Of String)()

                    Dim lName As String = pModul & "_" & aUnitName
                    lComponentsInit += Me.GetComponentInitsCode(lName)
                    Dim y As Integer
                    Dim rnd As New Random
                    y = rnd.Next(0, 480)
                    lComponentsSetting += Me.GetComponenttSettingsCode(lName, 50, y)

                    lComponentsAdd += Me.GetComponentAddsCode(lName)

                    lComponentsFriend += Me.GetComponentFriendsCode(lName)

                    lComponentClickCode += Me.GetComponentClicksCode(lName, aUnitName)

                    aResxFiles.Add(aFileNames.mPrefixFrm & aUnitName & aFileNames.mExtensionVBSource, aFileNames.mFolderModules & "\" & pModul & "\" & aFileNames.mPrefixFrm & aUnitName & aFileNames.mExtensionResx)
                    aVBFiles.Add(aFileNames.mFolderModules & "\" & pModul & "\" & aFileNames.mPrefixFrm & aUnitName & aFileNames.mExtensionVBSource)
                    aVBFiles.Add(aFileNames.mFolderModules & "\" & pModul & "\" & aFileNames.mPrefixLog & aUnitName & aFileNames.mExtensionVBSource)


                    Try
                        Me.aSolutionWorker.updateMainForm(Me.aPathDestination & "\" & Me.aProjectName & "\" & Me.aFileNames.mFileTplFrmMain, Me.aPathDestination & "\" & Me.aProjectName & "\" & Me.aFileNames.mFileTplFrmMainDesigner, lComponentsInit, lComponentsSetting, lComponentsAdd, lComponentsFriend, lComponentClickCode)
                    Catch e As Exception
                        MessageBox.Show("Chyba - Nepodarilo sa upravit Main Form " + e.Message)
                    End Try
                    Try
                        Me.aSolutionWorker.updateProjectFile(aPathDestination & "\" & aProjectName, aOtherFiles, aResxFiles, aVBFiles)
                    Catch e As Exception
                        MessageBox.Show("Chyba - Nepodarilo sa upravit Project File " + e.Message)
                    End Try
                End If
            End If
        Next
    End Sub
#End Region

#Region "property"
    Public Property DBGenerator() As DBGen
        Get
            Return aDbGen
        End Get
        Set(ByVal Value As DBGen)
            aDbGen = Value
        End Set
    End Property
    Public Property DBGeneratorSettings() As DBGenSettings
        Get
            Return aDbGenSettings
        End Get
        Set(ByVal Value As DBGenSettings)
            aDbGenSettings = Value
        End Set
    End Property
#End Region

#Region "Generate Only DB"
    Public Sub generateDB(ByVal pAllModulesDict As List(Of ModulAtributes))
        If (pAllModulesDict Is Nothing) Then
            MessageBox.Show("Nezvolili ste ziadne moduli na generovanie DB")
            Return
        End If
        If (pAllModulesDict.Count = 0) Then
            MessageBox.Show("Nezvolili ste ziadne moduli na generovanie DB")
            Return
        End If

        Dim aDlgDBGen As New DlgDBGenerator()
        If (Me.DBGeneratorSettings IsNot Nothing) Then    ' ak eksistuje uz nastavenie
            aDlgDBGen.SetComponents(Me.DBGeneratorSettings)
        End If
        aDlgDBGen.giveData(Me) ' prerobit na konstruktor a aby vracal denSettings ako navrat hodnotu
        aDlgDBGen.ShowDialog()

        Dim wantGenerate As Boolean = True

        If (Me.aDbGenSettings Is Nothing) Then
            MessageBox.Show("Nenastavili Ste generator - nebude vytvorena DB")
            wantGenerate = False
        End If
        If (wantGenerate = True) Then
            If (Me.DBGeneratorSettings.areSettingsCorrect() = False) Then
                MessageBox.Show("Nenastavili ste nastavenia pre Databázový generátor. Z tohto dôvodu nebude vygenerovana Databáza.")
            Else
                Me.DBGenerator.generateWholeDatabaseScript(Me.aDbGenSettings, pAllModulesDict)
                Try
                    If (wantGenerate = True) Then
                        SQL_worker.createDB(Me.aDbGenSettings.DbName, Me.DBGenerator.ScriptDatabaseCreate, Me.DBGenerator.ScriptTablesCreate, Me.DBGenerator.ScriptSystem, Me.DBGeneratorSettings.ServerName)
                    End If
                Catch e As Exception
                    MessageBox.Show("Chyba - Nepodarilo sa vytvorit Databazu " + e.Message)

                End Try

                If (aDbGenSettings.ScriptFileSave.Length > 5) Then
                    'ulozim do suboru db vygenerovane skripty
                    Me.aSolutionWorker = New SourceCode_worker()
                    Me.aSolutionWorker.WriteFileOnDisk(aDbGenSettings.ScriptFileSave, Me.DBGenerator.ScriptDatabaseCreate & vbCrLf & Me.DBGenerator.ScriptTablesCreate & vbCrLf & Me.DBGenerator.ScriptSystem)
                End If


            End If
        End If

    End Sub

#End Region

#Region "Generate From One Unit"
    ''' <summary>
    ''' generovanie jedneho z jedneho unitu
    ''' </summary>
    ''' <param name="pModules">Zoznam vsetkych modulov, potrebne na vytvorenie databazy</param>
    ''' <param name="pModul">nazov modulu z ktoreho sa ide generovat formular</param>
    ''' <param name="pModulHuman">analyticky nazov modulu</param>
    ''' <param name="pVersionName">nazov verzie</param>
    ''' <param name="pModulPath">cesta k suboru amod daneho modulu</param>
    ''' <param name="pUnit">nazov unitu z ktoreho ideme generovat formular</param>
    ''' <remarks></remarks>
    Public Sub GenerateOneFormProject(ByVal pMOdules As List(Of ModulAtributes), ByVal pModul As String, ByVal pModulHuman As String, ByVal pVersionName As String, ByVal pModulPath As String, ByVal pUnit As String)
        If (pModul.Length = 0) Then
            Throw New Exception("CHYBA - nazov modulu musi byt zadany")
            Return
        End If
        If (pModulPath.Length = 0) Then
            Throw New Exception("CHYBA - cesta k modulu musi byt zadana")
            Return
        End If
        If (pUnit.Length = 0) Then
            Throw New Exception("CHYBA - nazov unitu musi byt zadany")
            Return
        End If

        Dim codeHandler As CodeHandler
        codeHandler = New CodeHandler(aFileNames, Me.aPathRootTemplate, Me.aPathDestination, Me.aProjectName, Me.aSolutionName)
        If (codeHandler.existSolution()) Then ' ak existuje solution
            If (codeHandler.existForm(pModul, pUnit)) Then ' ak uz existuje formular
                ' ak existuje uz formular opytam sa ci ho mam prepisat alebo nie
                Dim reply As DialogResult = MessageBox.Show("Formulár '" + aFileNames.mPrefixFrm + pUnit + "' už existuje. Chcete ho nahradiť?", "Generovanie Formuláru", _
                  MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)

                If reply = DialogResult.Yes Then
                    ' vytvorim fomrular a nahradim
                    GenerateOneFormular(pMOdules, pModul, pModulHuman, pVersionName, pModulPath, pUnit, True)
                End If
            Else
                'vytvorim formular
                Dim aPathDestModul As String
                aPathDestModul = Me.aPathDestination & "\" & Me.aProjectName & "\" & Me.aFileNames.mFolderModules & "\" & pModul
                Dim aUnits As New List(Of String)
                aUnits.Add(pUnit)
                GenerateOneFormular(pMOdules, pModul, pModulHuman, pVersionName, pModulPath, pUnit, False)
                Me.aSolutionWorker.addFiles(Me.aPathRootTemplate & "\" & Me.aFileNames.mFolderSolutionFileTemplates, aPathDestModul, aUnits, Me.getUnitRegVw(pModul), Me.getUnitReg(aUnits), pModul)
                Dim lUnit As New List(Of String)
                lUnit.Add(pUnit)
                Try
                    Me.aSolutionWorker.updateModFile(pModul, Me.getUnitReg(lUnit))
                Catch e As Exception
                    MessageBox.Show("Chyba - Nepodarilo sa upravit Mod File " + e.Message)
                End Try
            End If
        Else ' ak neexistuje ziaden projekt
            Dim lModulsDict As List(Of ModulAtributes) = New List(Of ModulAtributes)
            lModulsDict.Add(New ModulAtributes(pModul, pModulHuman, pVersionName, pModulPath))
            GenerateProject(pMOdules, lModulsDict, pUnit)
        End If
    End Sub
#End Region



#Region "Generate Complet New Project"
    ''' <summary>
    ''' </summary>
    ''' <param name="pAllModulesDict">List(Of ModuleAtributes) ktora obsahuje informacie o kazdom module potrebne pre vytvorenie DB</param>
    ''' <param name="lModulesDict">List(Of ModuleAtributes) ktora obsahuje informacie o moduloch ktore sa maju generovat</param>
    ''' <param name="pUnit">nazov unitu, ak sa ide vytvarat cely projekt tak prazdny retazec</param>
    ''' <remarks></remarks>
    Public Sub GenerateProject(ByVal pAllModulesDict As List(Of ModulAtributes), ByVal lModulesDict As List(Of ModulAtributes), ByVal pUnit As String)

        If (lModulesDict.Count = 0) Then
            MessageBox.Show("Ziadne moduly na generovanie")
            Return
        End If

        Dim aOnlyForUnit As Boolean = False
        If (pUnit.Length > 0) Then
            aOnlyForUnit = True
        End If


        Dim axmodFilePath As String = ""
        Dim aOtherFiles As New List(Of String)()
        Dim aResxFiles As New Dictionary(Of String, String)
        Dim aVBFiles As New List(Of String)()

        'temporary

        Dim lComponentsInit As String = ""
        Dim lComponentsSetting As String = ""
        Dim lComponentsAdd As String = ""
        Dim lComponentsFriend As String = ""
        Dim lComponentClickCode As String = ""


        Dim x As Integer = 50
        Dim y As Integer = 50
        'temporary end

        Dim wantGenerate As Boolean = True



        ' vyskoci okno kde si nastavim cestu k kroslib projekte
        Dim aOfd As New OpenFileDialog()
        aOfd.Title = "KrosLib Projekt"
        aOfd.Filter = "VB Project Files (*.vbproj)|*.vbproj"
        aOfd.FileName = "D:\skola\Projekt\KrosLib\actual\SourceCode\KrosLib\KrosLib.vbproj"
        If (aOfd.ShowDialog() = DialogResult.OK) Then
            Me.aPathKroslibProject = aOfd.FileName
        End If

        ' nacitat settings pre DB Generator
        Dim aDlgDBGen As New DlgDBGenerator()
        If (Me.DBGeneratorSettings IsNot Nothing) Then    ' ak eksistuje uz nastavenie
            aDlgDBGen.SetComponents(Me.DBGeneratorSettings)
        End If
        aDlgDBGen.giveData(Me) ' prerobit na konstruktor a aby vracal denSettings ako navrat hodnotu
        aDlgDBGen.ShowDialog()

        Dim lPathAmodFilesForModuls As String = Me.aPathDestination

        Me.aModulesDict = New List(Of ModulAtributes)
        Me.aModulesDict = lModulesDict

        ' 1 krok - skopirovanie solution template na cielove miesto

        Try
            Me.aSolutionWorker.createSolution()
        Catch e As Exception
            MessageBox.Show("Chyba - Nepodarilo sa vytvorit Solution " + e.Message)
        End Try
        ' 2 krok - vygenerovanie databazy na disk na urcene miesto

        If (Me.aDbGenSettings Is Nothing) Then
            MessageBox.Show("Nenastavili Ste generator - nebude vytvorena DB")
            wantGenerate = False
        End If
        If (wantGenerate = True) Then
            If (Me.DBGeneratorSettings.areSettingsCorrect() = False) Then

                MessageBox.Show("Nenastavili ste nastavenia pre Databázový generátor. Z tohto dôvodu nebude vygenerovana Databáza.")

            Else

                Me.DBGenerator.generateWholeDatabaseScript(Me.aDbGenSettings, pAllModulesDict)

                Try
                    If (wantGenerate = True) Then




                        SQL_worker.createDB(Me.aDbGenSettings.DbName, Me.DBGenerator.ScriptDatabaseCreate, Me.DBGenerator.ScriptTablesCreate, Me.DBGenerator.ScriptSystem, Me.DBGeneratorSettings.ServerName)
                    End If
                Catch e As Exception
                    MessageBox.Show("Chyba - Nepodarilo sa vytvorit Databazu " + e.Message)

                End Try
            End If
        End If


        For Each lOneModule As ModulAtributes In Me.aModulesDict





            y = 50

            Dim aDat As Dat       ' dat vytvoreni nacitanim jednoho aMod suboru
            Dim aOneDataset As DsAModOneVersion ' dataset jednej verzie z ktoreho sa bude generovat databaza
            Dim aVersion As String
            Dim aPathDestModul As String
            aDat = New Dat(lOneModule.mModulName, lOneModule.mHumanModulName, lOneModule.mVersionName)

            ' 3 krok - pridanie formularov do adresarov modulov v novom projekte
            Dim aPathTemplateComponents As String = Me.aPathRootTemplate & "\" & Me.aFileNames.mFolderFormTemplates & "\" & Me.aFileNames.mFileFormComponents
            aDat.LoadDsComponents(aPathTemplateComponents)

            Me.aFrmGen = New GeneratorFormularov(Path.Combine(Me.aPathRootTemplate, Me.aFileNames.mFolderFormTemplates), aDat)
            aDat.LoadAMod(lOneModule.mPath, "CHYBA - Nepodarilo sa otvoriť Amod súbor pri generovaní databázy.")

            ' nastavi sa verzia a nacita konkretny dataset podla verzie
            If (wantGenerate = True) Then

                If (Me.aDbGenSettings.Ver = -1) Then
                    aVersion = aDat.GetLastVersion.ToString()
                    aOneDataset = aDat.GetVersionDataset(aVersion) 'ak ide o poslednu verziu
                Else
                    If (wantGenerate = False) Then
                        aVersion = -1
                    Else
                        aVersion = Me.aDbGenSettings.Ver
                    End If
                    aOneDataset = aDat.GetVersionDataset(aVersion)
                End If

            Else
                aVersion = aDat.GetLastVersion.ToString()
                aOneDataset = aDat.GetVersionDataset(aVersion)
            End If

            If (aOneDataset.Tables(aOneDataset.UnitsTable.TableName).Rows.Count < 0) Then
                aDat.AddMainView(aVersion)
            End If


            ' vytvorenie pohladu
            aDat.SaveAMod(aPathDestination & "\" & aProjectName & "\" & aFileNames.mFolderModules & "\" & lOneModule.mModulName & "\" & lOneModule.mModulName & aFileNames.mExtensionAmod, "Chyba - Nepodarilo sa ulozit Amod subor.")
            Dim aUnits As New List(Of String)
            Dim i As Integer = 0
            For Each aDataRow As DataRow In aOneDataset.Tables(aOneDataset.UnitsTable.TableName).Rows
                Dim aUnitName As String = (aDataRow("UnitName"))  'dano
                If (((aOnlyForUnit = True) And (pUnit = aUnitName)) Or (aOnlyForUnit = False)) Then
                    aUnits.Add(aUnitName)

                    'Dim aFrmFormulareExport As FrmFormulareExport = New FrmFormulareExport(Me.aPathDestination & "\" & Me.aProjectName & "\" & Me.aFileNames.mFolderModules & "\" & lOneModule.mModulName, aUnitName, aFrmGen, aExportSettings, aDat.GetLastVersion, "Zoznamovy Form")
                    'aFrmFormulareExport.ShowDialog()

                    Dim lMyPath As String = Me.aPathDestination & "\" & Me.aProjectName & "\" & Me.aFileNames.mFolderModules & "\" & lOneModule.mModulName
                    aFrmGen.Exportuj(aUnitName, lMyPath, aExportSettings, aDat.GetLastVersion)

                    i += 1

                    'temporary
                    ' budem lepit zdrojaky pre buttony aby som dokazal z hlavneho formularu otvorit vsetky formulare
                    Dim lName As String = lOneModule.mModulName & "_" & aUnitName
                    lComponentsInit += Me.GetComponentInitsCode(lName)

                    lComponentsSetting += Me.GetComponenttSettingsCode(lName, x, y)

                    lComponentsAdd += Me.GetComponentAddsCode(lName)

                    lComponentsFriend += Me.GetComponentFriendsCode(lName)

                    lComponentClickCode += Me.GetComponentClicksCode(lName, aUnitName)

                    'temporary koniec
                    y += 50

                    aResxFiles.Add(aFileNames.mPrefixFrm & aUnitName & aFileNames.mExtensionVBSource, aFileNames.mFolderModules & "\" & lOneModule.mModulName & "\" & aFileNames.mPrefixFrm & aUnitName & aFileNames.mExtensionResx)
                    aVBFiles.Add(aFileNames.mFolderModules & "\" & lOneModule.mModulName & "\" & aFileNames.mPrefixFrm & aUnitName & aFileNames.mExtensionVBSource)
                    aVBFiles.Add(aFileNames.mFolderModules & "\" & lOneModule.mModulName & "\" & aFileNames.mPrefixLog & aUnitName & aFileNames.mExtensionVBSource)
                End If
            Next



            aPathDestModul = Me.aPathDestination & "\" & Me.aProjectName & "\" & Me.aFileNames.mFolderModules & "\" & lOneModule.mModulName

            ' 4 krok - pridanie log,mod,dat suborov do adresarov modulov v novom projekte dano
            Me.aSolutionWorker.addFiles(Me.aPathRootTemplate & "\" & Me.aFileNames.mFolderSolutionFileTemplates, aPathDestModul, aUnits, Me.getUnitRegVw(lOneModule.mModulName), Me.getUnitReg(aUnits), lOneModule.mModulName)

            ' 5 krok - zhromazdenie vsetkcych suborov na ktore sa natiahnu referencie
            axmodFilePath = aFileNames.mFolderModules & "\" & lOneModule.mModulName & "\" & Me.aFileNames.mPrefixMod & lOneModule.mModulName & Me.aFileNames.mExtensionXmod

            ' 6 krok - pridanie referencii

            ' xmod a amod
            aOtherFiles.Add(aFileNames.mFolderModules & "\" & lOneModule.mModulName & "\" & lOneModule.mModulName & Me.aFileNames.mExtensionAmod)
            aOtherFiles.Add(aFileNames.mFolderModules & "\" & lOneModule.mModulName & "\" & Me.aFileNames.mPrefixMod & lOneModule.mModulName & Me.aFileNames.mExtensionXmod)

            ' mod dat log subory
            aVBFiles.Add(aFileNames.mFolderModules & "\" & lOneModule.mModulName & "\" & aFileNames.mPrefixDat & lOneModule.mModulName & aFileNames.mExtensionVBSource)
            aVBFiles.Add(aFileNames.mFolderModules & "\" & lOneModule.mModulName & "\" & aFileNames.mPrefixMod & lOneModule.mModulName & aFileNames.mExtensionVBSource)
            aVBFiles.Add(aFileNames.mFolderModules & "\" & lOneModule.mModulName & "\" & aFileNames.mPrefixLog & lOneModule.mModulName & aFileNames.mExtensionVBSource)

            ' formular zoznamovy
            aResxFiles.Add(aFileNames.mPrefixFrm & lOneModule.mModulName & aFileNames.mExtensionVBSource, aFileNames.mFolderModules & "\" & lOneModule.mModulName & "\" & aFileNames.mPrefixFrm & lOneModule.mModulName & aFileNames.mExtensionResx)
            aVBFiles.Add(aFileNames.mFolderModules & "\" & lOneModule.mModulName & "\" & aFileNames.mPrefixFrm & lOneModule.mModulName & aFileNames.mExtensionVBSource)


            aDat.ExportToXMod(aVersion, aPathDestination & "\" & aProjectName & "\" & aFileNames.mFolderModules & "\" & lOneModule.mModulName & "\" & aFileNames.mPrefixMod & lOneModule.mModulName & aFileNames.mExtensionXmod)
            

            aFrmGen.ExportujZoznamovyFormular("Zoznamovy Form", Me.aPathDestination & "\" & Me.aProjectName & "\" & Me.aFileNames.mFolderModules & "\" & lOneModule.mModulName, aExportSettings, aDat.GetLastVersion, aFileNames.mPrefixFrm & lOneModule.mModulName)

            lComponentsInit += Me.GetComponentInitsCode(lOneModule.mModulName)

            lComponentsSetting += Me.GetComponenttSettingsCode(lOneModule.mModulName, x, y)

            lComponentsAdd += Me.GetComponentAddsCode(lOneModule.mModulName)

            lComponentsFriend += Me.GetComponentFriendsCode(lOneModule.mModulName)

            lComponentClickCode += Me.GetComponentClicksCode(lOneModule.mModulName, lOneModule.mModulName)
            y += 50
            x += 200 ' temporary

        Next


        ' 7 krok - uprava inicializacneho suboru init
        Try

            Dim modulNames As New List(Of String)
            For Each modulAtr As ModulAtributes In lModulesDict
                modulNames.Add(modulAtr.mModulName)
            Next

            Dim serverName As String = ""
            Dim dbPath As String = ""
            Dim dbFileName As String = ""
            If (wantGenerate = True) Then
                serverName = Me.aDbGenSettings.ServerName
                dbPath = Me.aDbGenSettings.DbPath
                dbFileName = Me.aDbGenSettings.DBFileName
            End If
            Me.aSolutionWorker.updateInitFile(Me.aPathDestination & "\" & Me.aProjectName, serverName, dbPath & "\" & dbFileName & Me.aFileNames.mExtensionDbSql, "", "", modulNames.ToArray)

        Catch e As Exception
            MessageBox.Show("Chyba - Nepodarilo sa upravit Init File " + e.Message)
        End Try


        Try
            Me.aSolutionWorker.updateSolutionFile(Me.aPathDestination, Me.aPathKroslibProject, Me.aProjectName & "\" & Me.aFileNames.mFileTplProjectFile)
        Catch e As Exception
            MessageBox.Show("Chyba - Nepodarilo sa upravit Solution File " + e.Message)
        End Try
        'temporary
        Try
            Me.aSolutionWorker.updateMainForm(Me.aPathDestination & "\" & Me.aProjectName & "\" & Me.aFileNames.mFileTplFrmMain, Me.aPathDestination & "\" & Me.aProjectName & "\" & Me.aFileNames.mFileTplFrmMainDesigner, lComponentsInit, lComponentsSetting, lComponentsAdd, lComponentsFriend, lComponentClickCode)
        Catch e As Exception
            MessageBox.Show("Chyba - Nepodarilo sa upravit Main Form " + e.Message)
        End Try
        'temporary finish

        ' 8 krok - uprava projektoveho suboro pridanie referencii na subory vb, xmod, amod, log, dat, mod
        Try
            Me.aSolutionWorker.updateProjectFile(aPathDestination & "\" & aProjectName, aOtherFiles, aResxFiles, aVBFiles)
        Catch e As Exception
            MessageBox.Show("Chyba - Nepodarilo sa upravit Projekt File " + e.Message)
        End Try
        MessageBox.Show("Koniec generovania projektu", "Generovanie Projektu")
    End Sub
#End Region







#Region "Metody pre simulaciu generovania"

    ''' <summary>
    ''' Metoda vrati list objektov Dat, kazdy modul je predstavovany jednym objektom typu Dat
    ''' </summary>
    ''' <param name="pSolutionAmod">Dataset z ktoreho sa vytvori list Amodov typu Dat</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function getModulesForGenerating(ByVal pSolutionAmod As DsAmodSolution) As Dictionary(Of String, String)
        Dim aModulesDict As Dictionary(Of String, String) = New Dictionary(Of String, String)
        ' Me.mSolutionName = pSolutionAmod.ModulesDS(0).SolutionName  ' nastavim si meno ' dano
        ' prechadzanie datasetu a vytvorenie slovnka kde bude meno modulu a cesta k amod suboru

        For Each aModulDataRow As DataRow In pSolutionAmod.Modules
            aModulesDict.Add(aModulDataRow("ModuleName").ToString(), Path.Combine(Me.aPathDestination, aModulDataRow("RelativePath").ToString()))
        Next
        Return aModulesDict
    End Function

    Public Function getModulesListForGenerating(ByVal pSolutionAmod As DsAmodSolution) As List(Of ModulAtributes)
        Dim aModulesList As List(Of ModulAtributes) = New List(Of ModulAtributes)
        ' Me.mSolutionName = pSolutionAmod.ModulesDS(0).SolutionName  ' nastavim si meno ' dano
        ' prechadzanie datasetu a vytvorenie listu modulAtributes kde bude meno modulu a cesta k amod suboru, verzia, analyticke meno



        For Each aModulDataRow As DataRow In pSolutionAmod.Modules
            ' Dim ModulAtributes As New ModulAtributes(aModulDataRow(DsAMod.TableSysnames.Versions.Columns.ModulName).ToString(), aModulDataRow(DsAMod.TableSysnames.Versions.Columns.HumanModulName).ToString(), aModulDataRow(DsAMod.TableSysnames.Versions.Columns.RTFDescription).ToString(), Path.Combine(Me.aPathDestination, aModulDataRow("RelativePath").ToString()))

            Dim ModulAtributes As New ModulAtributes(aModulDataRow("ModuleName").ToString(), aModulDataRow("ModuleName").ToString(), "Description", Path.Combine(Me.aPathDestination, aModulDataRow("RelativePath").ToString()))
            aModulesList.Add(ModulAtributes)
            'aModulesDict.Add(aModulDataRow("ModuleName").ToString(), Path.Combine(Me.aPathDestination, aModulDataRow("RelativePath").ToString()))
        Next
        Return aModulesList
    End Function

#End Region
End Class
